﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Patterns.UnitOfWorkPattern
{
    public class TypeLookUp
    {
        protected static readonly Dictionary<Type, Type> EntityToContextDictionay
            = new Dictionary<Type, Type>();

        public static bool IsTypeCompatible(Type entityType, out Type contextType, out Type baseEntityType)
        {
            contextType = null;
            baseEntityType = null;

            if (!entityType.IsClass)
                return false;

            baseEntityType = entityType;

            while (baseEntityType != typeof(Object))
            {

                if (EntityToContextDictionay.TryGetValue(baseEntityType, out contextType))
                    return true;

                baseEntityType = entityType.BaseType;
            }

            return false;
        }
    }

    public class TypeLookUp<TContext> : TypeLookUp
    {
        public static void RegisterEntityType(Type entityType)
        {
            EntityToContextDictionay.Add(entityType, typeof(TContext));
        }

        public static bool IsTypeCompatible(Type entityType, out Type baseEntityType)
        {
            Type contextType;
            if (!IsTypeCompatible(entityType, out contextType, out baseEntityType))
                return false;

            return contextType == typeof(TContext);
        }
    }
}
